package com.sphere.freereader;


import android.app.ActionBar;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.astuetz.PagerSlidingTabStrip;
import com.sphere.freereader.adapter.MenuPopupAdapter;
import com.sphere.freereader.constant.Constants;
import com.sphere.freereader.entity.MenuPopupItem;
import com.sphere.freereader.utils.Helper;
import com.sphere.freereader.utils.NetWorkUtils;
import com.sphere.freereader.utils.PreferencesUtils;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener{


    private static final String TAG = "FreeReader";
    private ViewPager mViewPager;
    private PagerSlidingTabStrip mTabStrip;
    private List<Fragment> mContentFragments;

    private PopupWindow mPopupWindowSettings;
    private View mPopupSettingView;
    private static int[] mMenuSettingResIds;
    private static String[] mMenuSettingItems;

    private String[] mCategories;

    private boolean isNetworkConntected;
    private boolean isAllowUseMobileNetwork;
    private boolean isCurrentWifi;
    private boolean isFirstBootNetwork;
    private boolean isHadInitCompleted;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //super.handleMessage(msg);
            Log.d("tag", "result final = "  + msg.obj.toString());

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialValues();
        initialViews();
        initialActionbar();
        initialTabStripAttrs();
        //initialTabListener();
    }

    private void initialValues() {
        //mMenuSettingResIds = new int[]{R.mipmap.ic_launcher,R.mipmap.ic_launcher, R.mipmap.ic_launcher};
        mMenuSettingResIds = new int[]{0,0,0};
        mMenuSettingItems = getResources().getStringArray(R.array.setting_items);
        mCategories = getResources().getStringArray(R.array.book_category);
        isFirstBootNetwork = PreferencesUtils.getBoolean(this, Constants.START_NETWORK_FIRST_KEY, true);
    }

    private void initialViews() {
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabstrip);


    }

    private void initialActionbar() {
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowHomeEnabled(false);
        }
    }

    private void initialTabStripAttrs() {
        mTabStrip.setTextSize(Helper.dp2px(this, 16));
        mTabStrip.setIndicatorHeight(Helper.dp2px(this, 3));
        mTabStrip.setHideUnderLine(true);
        mTabStrip.setIndicatorHeight(6);
        mTabStrip.setBackgroundColor(getResources().getColor(R.color.slide_tab_bg_color));
    }


    private void initialFragments() {
        mContentFragments = new ArrayList<Fragment>();

        for (int i = 0; i < mCategories.length; i++) {
            mContentFragments.add(getFragmentSpec(i));
        }
        mViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), mContentFragments));
        mTabStrip.setViewPager(mViewPager);
        mTabStrip.setOnPageChangeListener(this);
        isHadInitCompleted = true;
    }

    private BookListFragment getFirstFragment() {
        return getFragmentSpec(0);
    }

    private BookListFragment getFragmentSpec(int position) {
        BookListFragment fragment = new BookListFragment();
        Bundle data = new Bundle();
        data.putString("category", mCategories[position]);
        data.putInt("position", position);
        fragment.setArguments(data);
        return fragment;
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        Log.d(TAG, "onPageSelected()  position = " + position);
        if (mContentFragments != null && mContentFragments.size() > 0) {
            ((BookListFragment)mContentFragments.get(position)).setLoadImmediately(true);
            ((BookListFragment)mContentFragments.get(position)).loadDataNow(true);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    @Override
    protected void onResume() {
        super.onResume();

        checkNetWorkConnected();
        if(!isFirstBootNetwork && !isHadInitCompleted) {
            initialFragments();
        }
        /*
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    Document document =
                        Jsoup.connect("http://www.sbkk8.cn/mingzhu/zhongguoxiandaiwenxuemingzhu/huangqueji/208063.html").get();
                    String htmlStr = document.html();
                    String result = HtmlParser.parseContentOfOneChapter(htmlStr);
                    Log.d("tag", "result = "  +result);
                    Message msg = mHandler.obtainMessage();
                    msg.obj = result;
                    msg.sendToTarget();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        */
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater mInflater = getMenuInflater();
        mInflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                if (mPopupSettingView == null) {
                    mPopupSettingView = findViewById(R.id.action_settings);
                }
                showSettingPopupWindow(mPopupSettingView);
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showSettingPopupWindow(final View parent) {
        if (mPopupWindowSettings == null) {
            View view = getLayoutInflater().inflate(R.layout.menu_home, null);
            ListView listView = (ListView) view.findViewById(R.id.lv_menu_popup);
            MenuPopupAdapter menuAddAdapter = new MenuPopupAdapter(this, initMenus(mMenuSettingResIds, mMenuSettingItems));
            listView.setAdapter(menuAddAdapter);
            mPopupWindowSettings = new PopupWindow(view, RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            initPopupWindow(mPopupWindowSettings);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    togglePopupWindow(mPopupWindowSettings, parent);
                }
            });
        }
        togglePopupWindow(mPopupWindowSettings, parent);
        }

    /**
     * 初始化右上角菜单的资源
     * @param resIds 图标资源数组
     * @param titles 菜单标题数组
     * @return 菜单列表
     */
    private List<MenuPopupItem> initMenus(int[] resIds, String[] titles) {
        List<MenuPopupItem> list = new ArrayList<MenuPopupItem>();
        int len = titles.length;
        for (int i = 0; i < len; i++) {
            //MenuPopupItem item = new MenuPopupItem(getResources().getDrawable(resIds[i]), titles[i]);
            MenuPopupItem item = new MenuPopupItem(new BitmapDrawable(null, (Bitmap)null), titles[i]);
            list.add(item);
        }
        return list;
    }

    private void initPopupWindow(PopupWindow popupWindow) {
        View view = popupWindow.getContentView();
        popupWindow.setWidth(Helper.getViewSize(view)[0]);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.update();
        popupWindow.setBackgroundDrawable(new BitmapDrawable(null, (Bitmap) null));
        popupWindow.setAnimationStyle(R.style.MenuPopupAnimStyle);
    }

    /**
     * 显示与消失popup菜单
     * @param window
     * @param parent
     */
    private void togglePopupWindow(PopupWindow window, View parent) {
        if (window.isShowing()) {
            window.dismiss();
        } else {
            if (parent != null) {
                window.showAtLocation(parent, Gravity.TOP | Gravity.RIGHT, 5,
                        Helper.getStatusBarHeight(this) + Helper.getActionBarHeight(this));
            }
        }
    }

    class MyPagerAdapter extends FragmentPagerAdapter {

        private final String[] TITLES = getResources().getStringArray(R.array.book_category);

        private List<Fragment> fragments;

        public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }
    }


    private void checkNetWorkConnected() {
        isNetworkConntected = NetWorkUtils.isConnected(this);
        if(!isNetworkConntected) {
            Helper.toastLong(this, getString(R.string.not_network));
            return;
        }

        isCurrentWifi = NetWorkUtils.isWifi(this);
        if(isNetworkConntected && !isCurrentWifi && isFirstBootNetwork) {
            showNetworkReminderDialog();
            PreferencesUtils.putBoolean(this, Constants.START_NETWORK_FIRST_KEY, false);
            isFirstBootNetwork = false;
        }else if(isNetworkConntected && isCurrentWifi){
            PreferencesUtils.putBoolean(this, Constants.START_NETWORK_FIRST_KEY, false);
            isFirstBootNetwork = false;
        }
    }


    private void showNetworkReminderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setPositiveButton("我偏要用流量", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isAllowUseMobileNetwork = true;
                        initialFragments();
                        //dialog.dismiss();
                    }
                })
                .setNegativeButton("我已切换到wifi", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                            initialFragments();
                    }
                })
                .setMessage("第一次加载会消耗一定的流量，建议在wifi环境下操作。");
        builder.setCancelable(false);
        builder.create();
        try {
            builder.show();
        }catch (Exception e) {
            Log.d(TAG, "error , dialog is null !");
            initialFragments();
        }

    }
}
